package com.escapeicon.bigevent.interceptors;

import com.escapeicon.bigevent.utils.JwtUtil;
import com.escapeicon.bigevent.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //前置拦截器
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            //获取用户携带 token 值
            String token = request.getHeader("Authorization");

            // 从 redis 中获取 token 进行对比
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String targetToken = operations.get(token);// 获取 token

            // 对比 token
            if (targetToken == null) {
                throw new RuntimeException();
            }

            // 将 token 中的信息存储于 安全线程中
            Map<String, Object> claims = JwtUtil.parseToken(token);
            ThreadLocalUtil.set(claims);
            //放行
            return true;
        } catch (Exception e) {
            //token解析异常则返回 401 响应
            response.setStatus(401);
            //不放行
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
